<template>
  <div ref="my_scroller" class="list_box flex">
    <scroller ref="myscroller" :on-infinite="infinite" :on-refresh="refresh">
      <BbsList ref="bbs_list" :type="type"/>
    </scroller>
  </div>
</template>

<script>
import BbsList from "@/components/home/BbsList.vue";

export default {
  // props: ['type', 'show'],
  data() {
    return {
      // type: 0
    };
  },
  components: {
    BbsList
  },
  computed: {
    type() {
      return this.$route.query.type || 0;
    }
  },
  created() {
    // this.type = this.$route.query.type;
  },
  watch: {},
  methods: {
    refresh() {
      console.log("refresh");
      this.$refs.bbs_list.refresh().then(() => {
        this.$refs.myscroller.finishPullToRefresh();
      })
      .catch(() => {
        this.$refs.myscroller.finishInfinite(true);
      });
    },
    infinite(done) {
      console.log("infinite");
      this.$refs.bbs_list
        .loadMore()
        .then(() => {
          this.$refs.myscroller.finishInfinite(false);
        })
        .catch(() => {
          this.$refs.myscroller.finishInfinite(true);
        });
    }
  },
  beforeRouteEnter(to, from, next) {
    // 进入
    if (!sessionStorage.askPositon) {
      sessionStorage.askPositon = "{}";
    }
    let askPositon = JSON.parse(sessionStorage.askPositon);
    if (!askPositon[to.query.type]) {
      askPositon[to.query.type] = 0;
      sessionStorage.askPositon = JSON.stringify(askPositon);
    }
    next(vm => {
      console.log('beforeRouteEnter', askPositon[vm.type]);
           setTimeout(function () {


      vm.$refs.myscroller.scrollTo(
        0,
        askPositon[vm.type]
      )}, 0);
    });
  },
  beforeRouteLeave(to, from, next) {
    // 离开
    let askPositon = JSON.parse(sessionStorage.askPositon);
    askPositon[this.type] =
      this.$refs.myscroller && this.$refs.myscroller.getPosition().top;
    sessionStorage.askPositon = JSON.stringify(askPositon);
    next();
  },
  beforeRouteUpdate(to, from, next) {
    let askPositon = JSON.parse(sessionStorage.askPositon);
    // 离开的时候记录滚动条位置
    askPositon[this.type] =
      this.$refs.myscroller && this.$refs.myscroller.getPosition().top;
    sessionStorage.askPositon = JSON.stringify(askPositon);
    // 进入的时候设置滚动条位置

    if (!askPositon[to.query.type]) {
      askPositon[to.query.type] = 0;
      sessionStorage.askPositon = JSON.stringify(askPositon);
    }

    this.$refs.myscroller.scrollTo(
      0,
      askPositon[to.query.type]
    ); //askPositon[vm.type];

    next();
  }
};
</script>
<style scoped lang="less">
.list_box {
  position: relative;
}
</style>
